EventListeners
Sources
Weiss, Appendix B
Summary
When the user types on the keyboard, or uses the mouse, the operating system produces an event. In Java, there are a few basic rules for using these events:
-
Any class that wants to respond to events must implement a listener interface.
-
Examples: ActionListener, WindowListener, MouseListener
-
Java.awt.event package has ‘listener adapter’ classes that you may extend instead of writing your own classes
-
In order for an object to handle an event, it must register with an add(type)Listener message which is sent to the calling method.
-
Then, you must implement an ActionPreformed method. This is called whenever an action is preformed.
-
Example: public void actionPreformed (ActionEvent e) {}
Example:
public class Beeper ... implements ActionListener {
...
//where initialization occurs:
button.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
...//Make a beep sound...
}
}